<template>
  <view class="cart-container">
    <!-- 顶部标题 -->
    <view class="cart-header">
      <text class="header-title">购物车</text>
      <text class="edit-btn" @click="toggleEditMode">{{ isEditMode ? '完成' : '编辑' }}</text>
    </view>

    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y v-if="cartList.length > 0">
      <view class="cart-item" v-for="item in cartList" :key="item.id">
        <!-- 选择框 -->
        <view class="select-box" @click="toggleSelect(item)">
          <view class="checkbox" :class="{ checked: item.selected }"></view>
        </view>

        <!-- 商品信息 -->
        <view class="goods-info" @click="goToGoodsDetail(item.goods_id)">
          <image :src="item.goods_image" class="goods-image" mode="aspectFill"></image>
          <view class="goods-detail">
            <text class="goods-name">{{ item.goods_name }}</text>
            <view class="goods-spec" v-if="item.specifications">
              <text class="spec-text">{{ formatSpecifications(item.specifications) }}</text>
            </view>
            <view class="leader-info">
              <text class="leader-name">{{ item.leader_name }}</text>
            </view>
            <view class="price-row">
              <text class="goods-price">¥{{ item.price }}</text>
              <view class="quantity-control">
                <uv-number-box 
                  v-model="item.quantity" 
                  min="1" 
                  :max="item.stock"
                  @change="updateQuantity(item)"
                  :disabled="isEditMode"
                ></uv-number-box>
              </view>
            </view>
          </view>
        </view>

        <!-- 删除按钮 -->
        <view class="delete-btn" v-if="isEditMode" @click="deleteItem(item)">
          <uv-icon name="trash" size="20" color="#ff4444"></uv-icon>
        </view>
      </view>
      <!-- 列表尾部占位，避免被底部栏遮挡 -->
      <!-- <view class="list-bottom-spacer"></view> -->
    </scroll-view>

    <!-- 空购物车 -->
    <view class="empty-cart" v-if="cartList.length === 0">
      <image src="https://placehold.co/200x200/png?text=%E7%A9%BA%E8%B4%AD%E7%89%A9%E8%BD%A6" class="empty-image" mode="aspectFit"></image>
      <text class="empty-text">购物车空空如也</text>
      <button class="go-shopping-btn" @click="goShopping">去逛逛</button>
    </view>

    <!-- 底部结算栏 -->
    <view class="bottom-bar" v-if="cartList.length > 0">
      <view class="select-all">
        <view class="select-box" @click="toggleSelectAll">
          <view class="checkbox" :class="{ checked: isAllSelected || isIndeterminate, indeterminate: isIndeterminate }"></view>
          <text class="select-text">全选</text>
        </view>
      </view>

      <view class="total-info" v-if="!isEditMode">
        <view class="total-row">
          <text class="total-label">合计：</text>
          <text class="total-price">¥{{ totalPrice }}</text>
        </view>
        <text class="total-desc">不含运费</text>
      </view>

      <view class="action-buttons">
        <button 
          class="delete-selected-btn" 
          v-if="isEditMode"
          @click="deleteSelected"
        >
          删除选中
        </button>
        <button 
          class="checkout-btn" 
          v-if="!isEditMode"
          :disabled="selectedCount === 0"
          @click="checkout"
        >
          结算({{ selectedCount }})
        </button>
      </view>
    </view>

    <!-- 推荐商品 -->
    <view class="recommend-section" v-if="cartList.length > 0">
      <view class="section-title">
        <text>为您推荐</text>
      </view>
      <scroll-view class="recommend-scroll" scroll-x>
        <view class="recommend-item" v-for="item in recommendGoods" :key="item.id" @click="goToGoodsDetail(item.id)">
          <image :src="item.image" class="recommend-image" mode="aspectFill"></image>
          <text class="recommend-name">{{ item.name }}</text>
          <text class="recommend-price">¥{{ item.price }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
// 使用 Vue3 <script setup> 重构（中文注释，变量/函数使用英文）
import { ref, computed, getCurrentInstance } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { cartApi, goodsApi } from '../../api/index.js'

// 全局方法（导航/提示）
const { proxy } = getCurrentInstance()

// 状态
const cartList = ref([])
const recommendGoods = ref([])
const isEditMode = ref(false)
const loading = ref(false)

// 计算属性
const isAllSelected = computed(() => cartList.value.length > 0 && cartList.value.every(item => item.selected))
const isIndeterminate = computed(() => {
  if (cartList.value.length === 0) return false
  const sel = cartList.value.filter(i => i.selected).length
  return sel > 0 && sel < cartList.value.length
})
const selectedCount = computed(() => cartList.value.filter(item => item.selected).length)
const totalPrice = computed(() => {
  const sum = cartList.value
    .filter(item => item.selected)
    .reduce((total, item) => total + (item.price * item.quantity), 0)
  return sum.toFixed(2)
})

// 初始化页面
const initPage = async () => {
  loadCartList()
  loadRecommendGoods()
}

// 加载购物车列表
const loadCartList = async () => {
  uni.showLoading({ title: '加载中...' })
  try {
    const data = await cartApi.getCartList()
    const stored = new Set((uni.getStorageSync('cartSelectedIds') || []).map(String))
    cartList.value = data.map(item => ({ ...item, selected: stored.has(String(item.id)) }))
  } catch (error) {
    proxy?.$showToast?.('加载失败')
  } finally {
    uni.hideLoading()
  }
}

// 加载推荐商品
const loadRecommendGoods = async () => {
  try {
    const data = await goodsApi.getHomeGoods()
    recommendGoods.value = data.recommend?.goods || []
  } catch (error) {
    console.error('加载推荐商品失败', error)
  }
}

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
}

// 切换商品选择
const toggleSelect = (item) => {
  item.selected = !item.selected
  saveSelection()
}

// 切换全选
const toggleSelectAll = () => {
  const newStatus = !isAllSelected.value
  cartList.value.forEach(item => { item.selected = newStatus })
  saveSelection()
}

// 更新商品数量
const updateQuantity = async (item) => {
  try {
    await cartApi.updateCartQuantity({ id: item.id, quantity: item.quantity })
  } catch (error) {
    proxy?.$showToast?.('更新失败')
    // 恢复原数量
    loadCartList()
  }
}

// 删除单个商品
const deleteItem = async (item) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await cartApi.removeFromCart([item.id])
          proxy?.$showToast?.('删除成功')
          loadCartList()
        } catch (error) {
          proxy?.$showToast?.('删除失败')
        }
      }
    }
  })
}

// 删除选中商品
const deleteSelected = async () => {
  const selectedIds = cartList.value.filter(item => item.selected).map(item => item.id)
  if (selectedIds.length === 0) {
    proxy?.$showToast?.('请选择要删除的商品')
    return
  }
  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的${selectedIds.length}个商品吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await cartApi.removeFromCart(selectedIds)
          proxy?.$showToast?.('删除成功')
          loadCartList()
        } catch (error) {
          proxy?.$showToast?.('删除失败')
        }
      }
    }
  })
}

// 结算
const checkout = () => {
  const selectedItems = cartList.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    proxy?.$showToast?.('请选择要结算的商品')
    return
  }
  const orderData = {
    items: selectedItems,
    total_amount: totalPrice.value
  }
  uni.setStorageSync('orderData', orderData)
  proxy?.$navigateTo?.('/pages/order/create/index')
}

// 格式化规格信息
const formatSpecifications = (specs) => {
  if (!specs) return ''
  return Object.values(specs).join('，')
}

// 跳转商品详情
const goToGoodsDetail = (goodsId) => {
  proxy?.$navigateTo?.(`/pages/goods/detail?id=${goodsId}`)
}

// 去购物
const goShopping = () => {
  proxy?.$switchTab?.('/pages/index/index')
}

// 选择状态持久化
const saveSelection = () => {
  const ids = cartList.value.filter(i => i.selected).map(i => i.id)
  uni.setStorageSync('cartSelectedIds', ids)
}

// 生命周期
onLoad(() => {
  initPage()
})
onShow(() => {
  loadCartList()
})
</script>

<style lang="scss" scoped>
.cart-container {
  min-height: 100vh;
  height: 100vh; // 让子元素可进行基于视窗的高度计算
  background-color: $uni-bg-color-grey;
  padding-bottom: 120rpx;
  display: flex;
  flex-direction: column;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx; // 明确头部高度
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid $uni-border-color;
  
  .header-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
  }
  
  .edit-btn {
    font-size: 28rpx;
    color: $uni-color-primary;
  }
}

.cart-list {
  background-color: transparent; // 由条目卡片承载背景
  padding: 20rpx 20rpx 0; // 两侧留白，底部改由占位元素处理
  min-height: 0; // 防止子元素撑高
  box-sizing: border-box;
  
  // 修复 H5 端 uni-scroll-view-content 默认最小高度导致溢出
  ::v-deep .uni-scroll-view-content {
    min-height: auto !important;
    height: auto !important;
  }
  // 保证滚动容器本身填满父容器剩余空间
  ::v-deep .uni-scroll-view {
    height: 100% !important;
  }
  
  .cart-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    border: 1rpx solid $uni-border-color;
    border-radius: 16rpx;
    background: #fff;
    box-shadow: 0 8rpx 22rpx rgba(0,0,0,0.05);
    margin-bottom: 16rpx;
    
    .select-box {
      margin-right: 20rpx;
      padding: 10rpx; // 扩大可点击区域
      display: flex;
      align-items: center;
      justify-content: center;

      .checkbox {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        border: 2rpx solid #ccc;
        position: relative;
        box-sizing: border-box;
        background: #fff;
        transition: all .2s ease;

        &::after {
          content: '';
          position: absolute;
          left: 10rpx;
          top: 4rpx;
          width: 12rpx;
          height: 22rpx;
          border: 4rpx solid #fff;
          border-top: 0;
          border-left: 0;
          transform: rotate(45deg);
          opacity: 0;
        }

        &.checked {
          background: #ff6b00;
          border-color: #ff6b00;
        }
        &.checked::after {
          opacity: 1;
        }

        &.indeterminate::after {
          left: 8rpx;
          top: 18rpx;
          width: 24rpx;
          height: 0;
          border: 0;
          opacity: 1;
          background: #fff;
        }
      }
    }
    
    .goods-info {
      flex: 1;
      display: flex;
      align-items: flex-start;
      
      .goods-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
        background: #f6f7f9; // 占位底色
      }
      
      .goods-detail {
        flex: 1;
        
        .goods-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
          overflow: hidden;
          display: -webkit-box;
          line-clamp: 2; // 标准属性
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-spec {
          margin-bottom: 10rpx;
          
          .spec-text {
            font-size: 24rpx;
            color: #999;
            background-color: #f5f5f5;
            padding: 4rpx 12rpx;
            border-radius: 10rpx;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap; // 规格单行省略
          }
        }
        
        .leader-info {
          margin-bottom: 15rpx;
          
          .leader-name {
            font-size: 24rpx;
            color: #666;
          }
        }
        
        .price-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .goods-price {
            font-size: 30rpx;
            color: $uni-color-primary;
            font-weight: bold;
          }
          
          .quantity-control {
            width: auto;
            min-width: 200rpx;
            text-align: right;
            
            // 调整 uv-number-box 尺寸
            ::v-deep .uv-number-box__input, 
            ::v-deep .uv-number-box__plus, 
            ::v-deep .uv-number-box__minus {
              height: 56rpx;
              line-height: 56rpx;
              font-size: 26rpx;
            }
          }
        }
      }
    }
    
    .delete-btn {
      margin-left: 20rpx;
      padding: 10rpx;
    }
  }
}


.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
  
  .go-shopping-btn {
    background-color: $uni-color-primary;
    color: #fff;
    border-radius: 40rpx;
    padding: 20rpx 60rpx;
    font-size: 28rpx;
    border: none;
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  border-top: 1rpx solid $uni-border-color;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  padding-bottom: constant(safe-area-inset-bottom); /* iOS < 11.2 */
  padding-bottom: env(safe-area-inset-bottom); /* iOS >= 11.2 */
  box-shadow: 0 -6rpx 18rpx rgba(0,0,0,0.06);
  
  .select-all {
    display: flex;
    align-items: center;
    margin-right: 30rpx;
    
    .select-box {
      margin-right: 10rpx;
    }
    
    .select-text {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .total-info {
    flex: 1;
    
    .total-row {
      display: flex;
      align-items: center;
      
      .total-label {
        font-size: 28rpx;
        color: #333;
      }
      
      .total-price {
        font-size: 32rpx;
        color: $uni-color-primary;
        font-weight: bold;
      }
    }
    
    .total-desc {
      font-size: 22rpx;
      color: #999;
    }
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .delete-selected-btn, .checkout-btn {
      height: 70rpx;
      border-radius: 35rpx;
      font-size: 28rpx;
      border: none;
      padding: 0 40rpx;
      min-width: 200rpx;
    }
    
    .delete-selected-btn {
      background-color: #ff4444;
      color: #fff;
    }
    
    .checkout-btn {
      background-color: #ff6b00;
      color: #fff;
      
      &:disabled {
        background-color: #ccc;
        color: #999;
      }
    }
  }
}

.recommend-section {
  margin: 20rpx;
  background-color: #fff;
  padding: 30rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  border-radius: 16rpx;
  margin-bottom: 140rpx; // 与底部栏保持距离
  
  .section-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 30rpx;
  }
  
  .recommend-scroll {
    white-space: nowrap;
    padding: 0 10rpx; // 两侧留白
    
    .recommend-item {
      display: inline-block;
      width: 220rpx;
      margin-right: 16rpx;
      text-align: left;
      vertical-align: top;
      background: #fff;
      border: 1rpx solid $uni-border-color;
      border-radius: 16rpx;
      box-shadow: 0 8rpx 22rpx rgba(0,0,0,0.05);
      padding: 12rpx;
      
      .recommend-image {
        width: 100%;
        height: 220rpx;
        border-radius: 12rpx;
        margin-bottom: 10rpx;
      }
      
      .recommend-name {
        font-size: 26rpx;
        color: #333;
        overflow: hidden;
        display: -webkit-box;
        line-clamp: 2; // 标准属性
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        margin: 6rpx 0 6rpx;
      }
      
      .recommend-price {
        font-size: 30rpx;
        color: $uni-color-primary;
        font-weight: 600;
      }
    }
  }
}
</style> 